package org.example.security.sso.common;


import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class DefaultExceptionHandler {

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.FORBIDDEN)
    public Map<String, Object> handleAccessDeniedException(AccessDeniedException e) {
        Map<String, Object> body = new HashMap<>(2);
        body.put("code", String.valueOf(HttpStatus.FORBIDDEN.value()));
        body.put("msg", HttpStatus.FORBIDDEN.getReasonPhrase() + " " + e.getLocalizedMessage());
        return body;
    }

    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    public Map<String, Object> handleAuthenticationException(AuthenticationException e) {
        Map<String, Object> body = new HashMap<>(2);
        body.put("code", String.valueOf(HttpStatus.UNAUTHORIZED.value()));
        body.put("msg", HttpStatus.UNAUTHORIZED.getReasonPhrase() + " " + e.getLocalizedMessage());
        return body;
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handleException(Exception e) {
        Map<String, Object> body = new HashMap<>(2);
        body.put("code", String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
        body.put("msg", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase() + " " + e.getLocalizedMessage());
        return body;
    }

}
